package com.amway.qy.core.service.impl;

import java.nio.charset.Charset;
import com.amway.qy.core.AccessTokenInfo;
import com.amway.qy.core.service.QyAccessTokenService;


/*
 * 由于 微信平台对Access Token 有一个调用次数限制，意味着access token必须 的一个缓存点，有可能是存放在DB有可能是存放在Redis之类的地方。
 * 
 * 本jar包默认使用的是内存中，如果在集群或者分布式下，需要自行继承该类，并实现具体的业务逻辑。
 * 
 */
public abstract class AbstractAccessTokenImpl implements QyAccessTokenService  {
 	
	protected static final Charset utf8 = Charset.forName("UTF-8");
	protected final AccessTokenInfo tokenInfo = new AccessTokenInfo();
	protected static Object lock = new Object();
	
	/*
	 * this is a abstract function to verify whether current token is expired or not.
	 * for the sub-class, need to provide the strategy 
	 */
	protected abstract boolean isExpired();
 
	/*
	 * this is function is only for retrieve the accessToken from DB or from Wechat websit.
	 */
	protected abstract String getAccessTokenDirect();
	
	@Override
	public String getAccessToken(){
		
		String ret = null;
		
		synchronized(lock){	
						
			if(tokenInfo.getCreateTime()!=null && !isExpired()){
				ret = tokenInfo.getAccess_token();
			}else{
				ret=getAccessTokenDirect();
			}
		}		
		return ret;
	}
	
	
	

}
